package com.example.util;

import java.sql.*;

//jdbc数据库连接工具类
public class JdbcUtil {
    //
    private static Connection connection=null;

    private static ResultSet resultSet=null;

    private static PreparedStatement preparedStatement=null;

    //mysql数据库相关连接
    static {
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url="jdbc:mysql://localhost:3306/crud?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false";
            String username= "root";
            String password= "123456";
            connection = DriverManager.getConnection(url, username, password);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static ResultSet getData(String sql, Object[] objects) {
        try {
            preparedStatement = connection.prepareStatement(sql);
            if (objects.length > 0) {
                for (int i = 0; i < objects.length; i++) {
                    preparedStatement.setObject(i + 1, objects[i]);
                }
            }
            resultSet =preparedStatement.executeQuery();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return resultSet;
    }


    public static int CRUData(String sql,Object[] objects){
        int num=0;
        try {
            preparedStatement= connection.prepareStatement(sql);
            for (int i = 0; i < objects.length; i++) {
                preparedStatement.setObject(i + 1, objects[i]);
            }
            num=preparedStatement.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }
        return num;
    }

    public static void connectionClose(){
        if (resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (preparedStatement!=null){
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
